package com.ljm.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author ChenHuaMing
 * 获取ip工具类
 */
public class IpUtils {
    private IpUtils(){}
    static final Logger logger = LoggerFactory.getLogger(IpUtils.class);
    private volatile static String ip;

    public static String getLocalIpAddress() {
        try {
            if(StringUtils.isEmpty(ip)){
                synchronized (IpUtils.class){
                    if(StringUtils.isEmpty(ip)){
                        InetAddress address = InetAddress.getLocalHost();
                        if(StringUtils.isNotEmpty(address.getHostAddress())){
                            ip=address.getHostAddress();
                        }
                    }
                }
            }
            return ip;
        } catch (UnknownHostException e) {
            logger.error("get ip error", e);
            return "localhost";
        }
    }
}
